<template>
  <div class="user">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span style="line-height: 36px;">用户管理</span>
        <el-button style="float: right;" type="primary" @click="dialogOpen('add')" v-if="USER.auth.indexOf('addUser')!==-1">新增用户</el-button>
      </div>
      <s-table
        :table="table"
        @http="tableWatch">
        <el-form-item slot="multiSelect" label="多选操作" prop="multiSelect" v-if="table.multiSelect">
          <el-row v-if="USER.auth.indexOf('lockedUser')!==-1">
            <el-col :span="8">
              <el-button size="small" type="success" @click="tableLockingUser(0)">启用用户</el-button>
            </el-col>
            <el-col :span="8" :offset="2">
              <el-button size="small" type="warning" @click="tableLockingUser(1)">锁定用户</el-button>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-button size="small" type="danger" @click="tableMultiDelete" v-if="USER.auth.indexOf('deleteUser')!==-1">多选删除</el-button>
            </el-col>
            <el-col :span="8" :offset="2">
              <el-button size="small" type="info" @click="tableResetPwd" v-if="USER.auth.indexOf('resetPwdUser')!==-1">重置密码</el-button>
            </el-col>
          </el-row>
        </el-form-item>
        <el-table-column
          fixed="right"
          align="center"
          slot="operation"
          class-name="operationMore"
          label="操作"
          width="80">
          <template scope="s">
            <el-button type="info" icon="edit" size="mini" @click="tableEdit(s.row)"></el-button>
            <el-tooltip placement="top">
              <div slot="content">更多可用操作</div>
              <el-popover
                popper-class="demo-table-expand"
                placement="right"
                title="更多可用操作"
                trigger="click">
                <slot name="content">
                  <div>
                    <el-button type="info" icon="search" size="mini" @click="dialogAuthSearchOpen(s.row)" v-if="USER.auth.indexOf('modUser')!==-1">权限详情</el-button>
                    <el-button type="danger" size="mini" @click="tableDelete(s.row)" v-if="USER.auth.indexOf('deleteUser')!==-1">删除用户</el-button>
                    <el-button type="info" size="mini" @click="dialogAddGroupOpen('put',s.row)" v-if="USER.auth.indexOf('groupAssign')!==-1">管理群组</el-button>
                    <el-button type="warning" size="mini" @click="dialogDatasOpen(s.row)" v-if="USER.auth.indexOf('dataAssign')!==-1">分配数据集</el-button>
                    <el-button :type="s.row.locked?'success':'danger'" size="mini" v-if="USER.auth.indexOf('lockedUser')!==-1" @click="tableLockingUser(s.row.locked>0?0:1,s.row.id)">{{s.row.locked>0?'启用':'禁用'}}用户</el-button>
                    <el-button size="mini" type="warning" v-if="USER.auth.indexOf('resetPwdUser')!==-1" @click="tableResetPwd(s.row)">重置密码</el-button>
                  </div>
                </slot>
                <el-button slot="reference" type="info" icon="more" :plain="true" size="mini" class="__reference"></el-button>
              </el-popover>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column
          width="40px"
          slot="moreTop"
          align="center"
          class-name="portrait"
          prop="photo">
          <template scope="s">
            <img :src="userPhoto + (s.row.photo||'base1.png')"
                 style="width: 24px;height: 24px;border-radius: 50%;float:left;"
                 alt="">
          </template>
        </el-table-column>
        <el-form-item label="用户名称" prop="userAccount">
          <el-input type="text"
                    class="input"
                    v-model="autoVueTable_userAccount"
                    placeholder="用户名称" spellcheck="false" auto-capitalize="off" auto-complete="off"
                    auto-correct="off"></el-input>
        </el-form-item>
      </s-table>
    </el-card>

    <s-dialog :dialog="dialog" :close="dialogInit">
      <p slot="title">{{dialog.title}}用户</p>
      <el-tabs v-model="dialog.activeName" @tab-click="handleClick" type="border-card">
        <el-tab-pane label="账号信息" :disabled="true">
          <s-form :form="formDialog0" ref="formDialog0">
            <el-form-item prop="photo" label="用户头像" class="form_item_user">
              <el-upload
                class="upload-user"
                name="userPhoto"
                :action="action"
                :show-file-list="false"
                :on-success="uploadUserSuccess"
                :before-upload="uploadUserUpload">
                <img v-if="formDialog0.photo" :src="formDialog0.photoURL || photo || 'base1.png'" class="avatar">
                <i v-else
                   class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </el-form-item>
            <el-form-item prop="userAccount"
                          v-if="dialog.title === '新增'"
                          label="用户账号">
              <el-input type="text"
                        v-model="formDialog0.userAccount"
                        placeholder="用户账号" spellcheck="false" auto-capitalize="off" auto-complete="off"
                        auto-correct="off"></el-input>
            </el-form-item>
            <el-form-item prop="userPassword"
                          label="登录密码"
                          v-if="dialog.title === '新增'"
                          :rules="[{ validator: validatePass, trigger: 'blur' }]">
              <el-input type="password"
                        v-model="formDialog0.userPassword"
                        placeholder="登录密码,不填为默认密码" spellcheck="false" auto-capitalize="off" auto-complete="off"
                        auto-correct="off"></el-input>
            </el-form-item>
            <el-form-item prop="userPassword2"
                          label="密码确认"
                          v-if="dialog.title === '新增'"
                          :rules="[{ validator: validatePass2, trigger: 'blur' }]">
              <el-input type="password"
                        v-model="formDialog0.userPassword2"
                        placeholder="密码确认" spellcheck="false" auto-capitalize="off" auto-complete="off"
                        auto-correct="off"></el-input>
            </el-form-item>
            <el-form-item prop="locked" label="锁定状态">
              <el-switch
                off-text="启用"
                on-text="锁定"
                v-model="formDialog0.locked"
                on-color="#ff4949"
                off-color="#13ce66">
              </el-switch>
            </el-form-item>
          </s-form>
        </el-tab-pane>
        <el-tab-pane label="基本信息" :disabled="true">
          <s-form :form="formDialog1" ref="formDialog1">
              <el-form-item prop="name" label="用户名称">
                <el-input type="text"
                          v-model="formDialog1.name"
                          placeholder="用户名称" spellcheck="false" auto-capitalize="off" auto-complete="off"
                          auto-correct="off"></el-input>
              </el-form-item>
            <el-form-item prop="type" label="用户类型">
              <el-select v-model="formDialog1.type" placeholder="请选择">
                <el-option
                  v-for="item in USER.type"
                  :key="item.dictionaryid"
                  :label="item.value"
                  :value="item.dictionaryid">
                </el-option>
              </el-select>
            </el-form-item>
              <el-form-item prop="rentId" label="所属客户">
                <el-select v-model="formDialog1.rentId" filterable placeholder="请选择">
                  <el-option
                    v-for="item in CUSTOM_customers"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item prop="orgId" label="所属机构">
                <el-select v-model="formDialog1.orgId"
                           filterable
                           multiple
                           remote
                           :remote-method="remoteMethodOrgId"
                           :loading="dialog.loading"
                           placeholder="请输入关键词">
                  <el-option
                    v-for="item in dialog.custom"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>
            <el-form-item prop="email"
                          :rules="[{ type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur,change' }]"
                          label="电子邮箱">
              <el-input type="text"
                        v-model="formDialog1.email"
                        placeholder="电子邮箱" spellcheck="false" auto-capitalize="off" auto-complete="off"
                        auto-correct="off"></el-input>
            </el-form-item>
            </s-form>
        </el-tab-pane>
      </el-tabs>
      <el-button slot="footer" @click="dialogPre" v-if="parseInt(dialog.activeName)!=0 ">上一步</el-button>
      <el-button slot="footer" @click="dialogNext" v-if="parseInt(dialog.activeName)<1 ">下一步</el-button>
      <el-button slot="footer" @click="dialogSave" v-if="parseInt(dialog.activeName)>=1 ">保存{{dialog.title==='新增'?'，并加入群组':''}}</el-button>
    </s-dialog>
    <s-dialog :dialog="dialogAddGroup" :close="dialogAddGroupInit">
      <p slot="title">{{dialogAddGroup.title}}群组<span>用户：{{ dialogAddGroup.name }}</span></p>
      <el-transfer
        :titles="['未加入群组','已加入群组']"
        class="__transfer"
        v-model="dialogAddGroup.ids"
        ref="transfer"
        filterable
        :filter-method="transferFilterMethod"
        :render-content="transferRenderContent"
        filter-placeholder="请输入 -n 名称,-a 应用,-c 客户"
        @click.native="transferClickColor"
        :data="GROUP_group"></el-transfer>
      <el-button slot="footer" @click="dialogAddGroupSave">加入群组</el-button>
    </s-dialog>
    <s-dialog :dialog="dialogDatas" :close="dialogDatasInit">
      <p slot="title">{{dialogDatas.title}}<span>{{'用户名：' + dialogDatas.row.name}}</span></p>
      <el-transfer
        :titles="['未添加数据集','已添加数据集']"
        class="__transfer"
        v-model="dialogDatas.ids"
        ref="transferDatas"
        filterable
        :filter-method="transferFilterMethodDatas"
        :render-content="transferRenderContentDatas"
        filter-placeholder="请输入 -n 数据集名称,-p 数据项名称"
        @click.native="transferClickColorDatas"
        :data="dialogDatas.data">
        <span slot="left-footer" class="__transfer_footer">
          <el-button class="transfer-footer _refresh" size="small" :loading="dialogDatas.refresh" @click="dialogDatasRefresh"><i v-show="!dialogDatas.refresh" :class="['fa','fa-refresh','fa-fw', 'refresh']"></i> 刷新</el-button>
          <el-button class="transfer-footer" type="success" size="small" @click="windowOpen" v-if="USER.auth.indexOf('datas')!==-1">管理数据集</el-button>
        </span>
      </el-transfer>
      <el-button slot="footer" type="info" @click="dialogDatasSave">保存</el-button>
    </s-dialog>
    <s-dialog :dialog="dialogAuthSearch" :close="dialogAuthSearchInit" :closeTip="false">
      <p slot="title">{{dialogAuthSearch.title}}<span>{{'用户名称：' + dialogAuthSearch.row.name}}</span></p>
      <s-table :table="tableAuthSearch"
               @expand="tableAuthSearchExpand"
               @http="tableWatch">
        <el-form-item label="应用名称" prop="aName">
          <el-input type="text"
                    class="input"
                    :expandFuc="tableAuthSearchExpand"
                    v-model="autoVueTable_aName"
                    placeholder="应用名称" spellcheck="false" auto-capitalize="off" auto-complete="off"
                    auto-correct="off"></el-input>
        </el-form-item>
        <el-form-item label="应用编号" prop="aCode">
          <el-input type="text"
                    class="input"
                    v-model="autoVueTable_aCode"
                    placeholder="应用编号" spellcheck="false" auto-capitalize="off" auto-complete="off"
                    auto-correct="off"></el-input>
        </el-form-item>
        <el-table-column
          type="expand"
          slot="expand"
          width="40px"
          class-name="expand"
          fixed="left">
          <template scope="s">
            <el-row>
              <el-col :xs="24" :lg="{span: 10, offset: 0}">
                <p>功能权限</p>
                <el-tree :data="s.row.func"></el-tree>
              </el-col>
              <el-col :xs="24" :lg="{span: 10, offset: 2}">
                <p>数据权限</p>
                <el-tree :data="s.row.datas"></el-tree>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
      </s-table>
      <el-button slot="footer" type="info" @click="dialogAuthSearchSave">好</el-button>
    </s-dialog>
    <s-dialog :dialog="dialogSearchSearch" :close="dialogSearchSearchInit" :closeTip="false">
      <p slot="title">{{dialogSearchSearch.title}}数据集<span>{{dialogSearchSearch.datasname + ':' + dialogSearchSearch.dName}}</span></p>
      <s-form :form="formDialogSearchSearch" ref="formDialogSearchSearch">
        <el-form-item prop="ids" label="数据集内容">
          <el-tree
            ref="tree1"
            :data="dialogSearchSearch.tree.data"
            node-key="key">
          </el-tree>
        </el-form-item>
      </s-form>
      <el-button slot="footer" type="primary" @click="dialogSearchSearchOk">好</el-button>
    </s-dialog>
  </div>
</template>

<script>
  import {AutoVue, AutoPromise} from '~/plugins/Tools';
  import Config from '~/config';
  const axiosLocal = Config.Local.interface;
  const PublicImageServer = Config.PublicImageServer;

  function __form0 () {
    return {
      photo: {value: '', rule: [], notes: '用户头像'},
      photoURL: {value: '', rule: [], notes: '用户头像过度'},
      locked: {value: false, rule: [], notes: '锁定状态'},
      userAccount: {value: '', rule: ['vNull'], notes: '登录账号'},
      userPassword: {value: '', rule: [], notes: '登录密码'},
      userPassword2: {value: '', rule: [], notes: '密码确认'},
    };
  }

  function __form1 () {
    return {
      name: {value: '', rule: ['vNull'], notes: '用户姓名'},
      type: {value: 1, rule: [], notes: '用户类型'},
      rentId: {value: 0, rule: ['vNull'], notes: '所属客户'},
      orgId: {value: [], rule: ['vNull'], notes: '所属机构'},
      email: {value: '', rule: [], notes: '电子邮箱'},
    };
  }
  function __formDialogSearchSearch () {
    return {
      id: {value: 0},
      dName: {value: '', rule: ['vNull']},
      ids: {value: [], rule: []},
    };
  }

  export default AutoVue({
    name: 'user-safety',
    store: ['DICTIONARY_user', 'USER', 'CUSTOM_customers', 'GROUP_group'],
    data: {
      axiosLocal,
      table: {
        column: [
          {label: '账号', prop: 'userAccount', minWidth: '0px', search: true},
          {label: '姓名', prop: 'name', minWidth: '0px'},
          {label: '所属客户', prop: 'show_rent', minWidth: '0px'},
          {label: '所属组织', prop: 'orgName', minWidth: '0px'},
          {
            label: '锁定状态',
            prop: 'locked',
            minWidth: '0px',
            elTag: {
              filterType: function (value) {
                return parseInt(value) === 0 ? 'success' : 'danger';
              },
            },
            formatter: (row, column) => {
              return parseInt(row[column.property || column]) === 0 ? '未锁定' : '锁定';
            },
          },
          {label: '用户类型', prop: 'show_type', minWidth: '0px'},
          {label: '电子邮箱', prop: 'email', minWidth: '0px'},
          {
            label: '创建时间',
            prop: 'createDate',
            minWidth: '0px',
            formatter: (row, column) => {
              return this.a.methods.formatterTime(row[column.property || column], 1);
            },
          },
        ],
        url: '/user/',
        key: 'id',
        tableColumn: 5,
      },
      formDialog0: __form0(),
      formDialog1: __form1(),
      dialog: {
        title: '新增',
        activeName: '0',
        optionFormStep: {
          id: 0,
        },
        custom: [],
        orgId: [],
        loading: false,
      },
      dialogAddGroup: {
        title: '加入',
        size: 'large',
        name: '',
        id: 0,
        ids: [],
        idsOld: [],
      },
      dialogDatas: {
        title: '用户分配数据集',
        size: 'large',
        row: {},
        ids: [],
        idsOld: [],
        data: [],
        refresh: false,
      },

      tableAuthSearch: {
        column: [
          {
            label: '应用名称',
            prop: 'aName',
            minWidth: '120px',
            search: true,
          },
          {
            label: '应用编号',
            prop: 'aCode',
            minWidth: '120px',
            search: true,
          },
        ],
        url: '/app/',
        key: 'id',
        tableColumn: 2,
        expand: true,
        muti: false,
        cb (json) {
          let {data, total} = json;
          for (let item of data) {
            item.func = [];
            item.data = [];
          }
          this['tableAuthSearch'].data = data;
          this['tableAuthSearch'].total = total;
        },
      },
      dialogAuthSearch: {
        title: '权限',
        row: {},
        size: 'large',
      },
      dialogSearchSearch: {
        title: '新增',
        formRef: 'formDialogSearchSearch',
        tree: {
          data: [],
          size: 0,
        },
        datasname: '',
        dName: '',
      },
      formDialogSearchSearch: __formDialogSearchSearch(),
    },
    transition: 'slide-fade',
    computed: {
      userPhoto: function () {
        return PublicImageServer.src + '/image/userPhoto/';
      },
      photo: function () {
        if (this.USER.user.photo) {
          return PublicImageServer.src + '/image/userPhoto/' + this.USER.user.photo;
        } else {
          return this.USER.user.gender === '女' ? '/image/users/base2.png' : '/image/users/base1.png';
        }
      },
      action: function () {
        let params = '';
        if (this.formDialog0.photo && this.formDialog0.photo !== 'base1.png' && this.formDialog0.photo !== 'base2.png') {
          params = '?imageOldName=' + this.formDialog0.photo;
        }
        return PublicImageServer.src + `/${PublicImageServer.upload}/${PublicImageServer.userPhoto}` + params;
      },
    },
    methods: {
      validatePass: function (rule, value, callback) {
        if ((value + '').length < 6 && (value + '').length !== 0) {
          if (this.formDialog0.userPassword2 !== '') {
            this.$refs.formDialog0.$refs.formDialog0.validateField('userPassword2');
          }
          callback(new Error('请输入不少于6位的密码'));
        } else {
          if (this.formDialog0.userPassword2 !== '') {
            this.$refs.formDialog0.$refs.formDialog0.validateField('userPassword2');
          }
          callback();
        }
      },
      validatePass2: function (rule, value, callback) {
        if (this.formDialog0.userPassword === '') {
          this.formDialog0.userPassword2 = '';
          callback();
        }
        if (value === '') {
          callback(new Error('请再次输入密码'));
        } else if (value !== this.formDialog0.userPassword) {
          callback(new Error('两次输入密码不一致!'));
        } else {
          callback();
        }
      },
      tableEdit (row) {
        this.dialogOpen('PUT', row);
      },
      tableDelete (row) {
        this.$confirm('您将删除用户。', '确认删除？', {
          confirmButtonText: '是',
          cancelButtonText: '否',
          type: 'warning',
        })
          .then(async _ => {
            try {
              await this.post('/user/delete/', [row.id]);
              this.tableWatch('table');
            } catch (err) {
              console.log(err);
            }
          })
          .catch(_ => {
          });
      },
      tableMultiDelete () {
        this.$confirm('您将删除这些用户。', '确认删除？', {
          confirmButtonText: '是',
          cancelButtonText: '否',
          type: 'warning',
        })
          .then(async _ => {
            let step = [];
            for (let item of this.table.multipleSelection) {
              step.push(item.id);
            }
            try {
              await this.post('/user/delete/', step);
              this.tableWatch('table');
            } catch (err) {
              console.log(err);
            }
          })
          .catch(_ => {
          });
      },
      tableLockingUser (state, id) {
        this.$confirm(`您将${state ? '锁定' : '启用'}这些用户。`, '是否确认？', {
          confirmButtonText: '是',
          cancelButtonText: '否',
          type: 'warning',
        })
          .then(async _ => {
            let step = [];
            if (typeof id === 'undefined') {
              for (let item of this.table.multipleSelection) {
                step.push(item.id);
              }
            } else {
              step.push(id);
            }
            try {
              await this.post('/user/lockingUser', {
                ids: step,
                state,
              });
              this.tableWatch('table');
            } catch (err) {
              console.log(err);
            }
          })
          .catch(_ => {
          });
      },
      tableResetPwd (row) {
        this.$confirm('您将重置用户密码。', '是否确认？', {
          confirmButtonText: '是',
          cancelButtonText: '否',
          type: 'warning',
        })
          .then(async _ => {
            let step = [];
            if (!row) {
              for (let item of this.table.multipleSelection) {
                step.push(item.id);
              }
            } else {
              step.push(row.id);
            }
            try {
              await this.post('/user/resetPwd', step);
              this.tableWatch('table');
            } catch (err) {
              console.log(err);
            }
          })
          .catch(_ => {
          });
      },
      dialogInit () {
        this.dialog.optionFormStep = {
          id: 0,
        };
        this.dialog.activeName = '0';
        this.dialog.orgId = [];
        this.formDialog0 = {
          ...this.formDialog0,
          ...this.ObjectClone(__form0()),
        };
        this.formDialog1 = {
          ...this.formDialog1,
          ...this.ObjectClone(__form1()),
        };
        this.resetFields('formDialog0');
        this.resetFields('formDialog1');
      },
      async dialogOpen (type, more) {
        if (type) {
          type = type.toUpperCase();
        } else return;
        await AutoPromise([
          async () => {
            if (this.CUSTOM_customers.length === 0) {
              let data = await this.get('/custom/');
              this.SET('CUSTOM', data);
            }
          },
          async () => {
            if (!this.DICTIONARY_user) {
              await this.USE('DICTIONARY_user');
            }
          },
        ]);
        switch (type) {
        case 'ADD':
          this.dialog.title = '新增';
          this.formDialog1.rentId = this.USER.user.rentId;
          break;
        case 'PUT':
          this.dialog.title = '修改';
          for (let index in more) {
            if (!more.hasOwnProperty(index)) continue;
            if (index === 'orgId') {
              this.dialog.orgId = more[index];
            }
            if (typeof this.formDialog0[index] !== 'undefined') {
              this.formDialog0[index] = more[index];
            } else if (typeof this.formDialog1[index] !== 'undefined') {
              this.formDialog1[index] = more[index];
            } else {
              this.dialog.optionFormStep[index] = more[index];
            }
          }
          this.formDialog0.locked = !!this.formDialog0.locked;
          break;
        }
        this.dialog.visible = true;
      },
      dialogSave () {
        // let more = this.dialog.saveParameter;
        if (this.dialog.title === '新增') {
          this.VALIDATE('formDialog1', async option => {
            this.dialog.optionFormStep = {
              ...this.dialog.optionFormStep,
              ...option,
            };
            this.dialog.optionFormStep.locked = this.dialog.optionFormStep.locked ? 1 : 0;
            this.dialog.optionFormStep.photo = this.dialog.optionFormStep.photo || 'base1.png';
            try {
              let {id} = await this.post('/user/add', this.dialog.optionFormStep);
              let json = await this.get('user/' + id);
              this.table.data = [json, ...this.table.data];
              this.table.total++;
              this.dialogInit();
              this.dialog.visible = false;
              if (this.USER.auth.indexOf('groupAssign') !== -1) {
                this.dialogAddGroupOpen('add', json);
              }
            } catch (err) {
              console.log(err);
            }
          });
        } else {
          this.VALIDATE('formDialog1', async option => {
            this.dialog.optionFormStep = {
              ...this.dialog.optionFormStep,
              ...option,
            };
            this.dialog.optionFormStep.locked = this.dialog.optionFormStep.locked ? 1 : 0;
            try {
              await this.post('/user/add', this.dialog.optionFormStep);
              let id = this.dialog.optionFormStep.id;
              let json = await this.get('/user/' + id);
              for (let i = 0; i < this.table.data.length; i++) {
                if (this.table.data[i].id === id) {
                  for (let index in this.table.data[i]) {
                    if (this.table.data[i].hasOwnProperty(index)) {
                      this.table.data[i][index] = json[index];
                    }
                  }
                }
              }
              this.dialogInit();
              this.dialog.visible = false;
            } catch (err) {
              console.log(err);
            }
          });
        }
      },
      dialogAddGroupInit () {
        this.dialogAddGroup.title = '加入';
        this.dialogAddGroup.name = '';
        this.dialogAddGroup.id = 0;
        this.dialogAddGroup.ids = [];
        this.dialogAddGroup.idsOld = [];
      },
      async dialogAddGroupOpen (type, more) {
        let {
          id,
          rentId,
          name,
        } = more;
        if (type) {
          type = type.toUpperCase();
        } else return;
        switch (type) {
        case 'ADD':
          this.dialogAddGroup.title = '加入';
          if (this.GROUP_group.length < 1) {
            try {
              let {data} = await this.get('/grpm/usergroupall/' + rentId);
              this.SET('GROUP', data);
            } catch (err) {
              console.log(err);
            }
          }
          break;
        case 'PUT':
          this.dialogAddGroup.title = '修改';
          await AutoPromise([
            async () => {
              try {
                let {data} = await this.get('/grpm/usergroupall/' + rentId);
                this.SET('GROUP', data);
              } catch (err) {
                console.log(err);
              }
            },
            async () => {
              try {
                let {ids} = await this.get('/grpm/usergroup/' + id);
                this.dialogAddGroup.ids = ids;
                this.dialogAddGroup.idsOld = ids;
              } catch (err) {
                console.log(err);
              }
            },
          ]);
          break;
        }
        this.dialogAddGroup.id = id;
        this.dialogAddGroup.name = name;
        this.dialogAddGroup.visible = true;
      },
      dialogAddGroupSave: async function () {
        let add = [];
        let del = [];
        for (let item of this.dialogAddGroup.ids) {
          if (this.dialogAddGroup.idsOld.indexOf(item) === -1) {
            add.push(item);
          }
        }
        for (let item of this.dialogAddGroup.idsOld) {
          if (this.dialogAddGroup.ids.indexOf(item) === -1) {
            del.push(item);
          }
        }
        try {
          await this.post('/grpm/changegroup', {
            id: this.dialogAddGroup.id,
            add,
            del,
          });
          this.dialogAddGroupInit();
          this.dialogAddGroup.visible = false;
        } catch (err) {
          console.log(err);
        }
      },
      dialogNext () {
        this.VALIDATE('formDialog' + this.dialog.activeName, function (option) {
          delete option.userPassword2;
          delete option.photoURL;
          if (this.dialog.orgId.length !== 0) {
            this.formDialog1.orgId = this.dialog.orgId;
          }
          this.dialog.optionFormStep = {
            ...this.dialog.optionFormStep,
            ...option,
          };
          this.dialog.activeName = parseInt(this.dialog.activeName) + 1 + '';
        });
      },
      dialogPre () {
        this.dialog.activeName = parseInt(this.dialog.activeName) - 1 + '';
      },
      handleClick (tab, event) {
        console.log(tab, event);
      },
      remoteMethodOrgId: async function (query) {
        if (!this.formDialog1.rentId) return;
        this.dialog.loading = true;
        this.dialog.custom = await this.get(`/org/${this.formDialog1.rentId}/getOrgByName/${query || '0000000000'}`);
        this.dialog.loading = false;
      },
      transferClickColor () {
        setTimeout(() => {
          Array.from(this.$refs.transfer.$el.querySelectorAll('.el-transfer-panel__item')).forEach(div => {
            div.classList[!div.querySelector('span.is-checked') ? 'remove' : 'add']('checked');
          });
        }, 100);
      },
      transferFilterMethod (query, item) {
        if (query.indexOf('-') === 0) {
          let step = [];
          query.split(' ').find(q => {
            step.push(q.trim());
          });
          switch (step[0]) {
          case '-n':
          case '-N':
            return item.name.indexOf(step[1]) > -1;
          case '-A':
          case '-a':
            return item.show_appId.indexOf(step[1]) > -1;
          case '-c':
          case '-C':
            return item.show_rentId.indexOf(step[1]) > -1;
          default:
            return true;
          }
        } else {
          return (item.name.indexOf(query) > -1 || item.show_appId.indexOf(query) > -1 || item.show_rentId.indexOf(query) > -1);
        }
      },
      transferRenderContent (h, option) {
        return (
          <div>
            <span class="label name">{option.name}</span>
            <span class="label show_appId">{option.show_appId}</span>
            <span class="label show_rentId">{option.show_rentId}</span>
          </div>
        );
      },
      transferShow (event, option) {
        this.dialogSearchSearchOpen(option);
        event.stopPropagation();
      },

      async dialogSearchSearchOpen (row) {
        this.dialogSearchSearch.title = '查看';
        this.dialogSearchSearch.datasname = row.datasname;
        this.dialogSearchSearch.dName = row.label;
        this.dialogSearchSearch.tree.data = await this.get('/datasetImpl/' + row.key);
        for (let index in this.formDialogSearchSearch) {
          if (this.formDialogSearchSearch.hasOwnProperty(index)) {
            if (typeof row[index] !== 'undefined') {
              this.formDialogSearchSearch[index] = row[index];
            }
          }
        }
        this.dialogSearchSearch.visible = true;
      },
      dialogSearchSearchOk () {
        this.dialogSearchSearchInit();
        this.dialogSearchSearch.visible = false;
      },
      dialogSearchSearchInit () {
        this['formDialogSearchSearch'] = {
          ...this['formDialogSearchSearch'],
          ...this.ObjectClone(__formDialogSearchSearch()),
        };
        this.dialogSearchSearch.tree.data = [];
        this.dialogSearchSearch.tree.datasname = '';
        this.dialogSearchSearch.tree.dName = '';
      },
      uploadUserSuccess (res, file) {
        this.formDialog0.photoURL = URL.createObjectURL(file.raw);
        this.formDialog0.photo = res.filename;
        if (res.error) {
          return this.$alert(res.error);
        }
        if (this.dialog.title === '新增') return;
        this.post('/user/updateImg', {
          userId: this.USER.user.id,
          path: res.filename,
        });
        this.SET('USER_photo', res.filename);
      },
      uploadUserUpload (file) {
        const isJPG = file.type === 'image/jpeg';
        const isPNG = file.type === 'image/png';
        const isLt2M = file.size / 1024 / 1024 < 2;
        if (!isJPG && !isPNG) {
          this.$message.error('上传头像图片只能是 JPG 与 PNG 格式!');
        }
        if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 2MB!');
        }
        return (isJPG || isPNG) && isLt2M;
      },

      dialogDatasInit () {
        this.dialogDatas.row = {};
        this.dialogDatas.ids = [];
        this.dialogDatas.idsOld = [];
        this.dialogDatas.data = [];
        this.dialogDatas.refresh = false;
      },
      async dialogDatasOpen (row) {
        let {ids, contentList} = await this.get('/userdataset/' + row.id);
        this.dialogDatas.row = row;
        this.dialogDatas.ids = ids;
        this.dialogDatas.idsOld = ids;
        this.dialogDatas.data = contentList;
        this.dialogDatas.visible = true;
      },
      async dialogDatasRefresh () {
        this.dialogDatas.refresh = true;
        let {contentList} = await this.get('/userdataset/' + this.dialogDatas.row.id);
        this.dialogDatas.data = contentList;
        this.dialogDatas.refresh = false;
      },
      dialogDatasSave: async function () {
        let {ids, idsOld, row} = this.dialogDatas;
        let add = [];
        let del = [];
        for (let item of ids) {
          if (idsOld.indexOf(item) === -1) {
            add.push(item);
          }
        }
        for (let item of idsOld) {
          if (ids.indexOf(item) === -1) {
            del.push(item);
          }
        }
        try {
          await this.post('/userdataset/add', {
            id: row.id,
            add,
            del,
          });
          this.dialogDatasInit();
          this.dialogDatas.visible = false;
        } catch (err) {
          console.log(err);
        }
      },

      transferClickColorDatas () {
        setTimeout(() => {
          Array.from(this.$refs.transferDatas.$el.querySelectorAll('.el-transfer-panel__item')).forEach(div => {
            div.classList[!div.querySelector('span.is-checked') ? 'remove' : 'add']('checked');
          });
        }, 100);
      },
      transferFilterMethodDatas (query, item) {
        if (query.indexOf('-') === 0) {
          let step = [];
          query.split(' ').find(q => {
            step.push(q.trim());
          });
          switch (step[0]) {
          case '-n':
          case '-N':
            return item.label.indexOf(step[1]) > -1;
          case '-p':
          case '-P':
            return item.datasname.indexOf(step[1]) > -1;
          default:
            return true;
          }
        } else {
          return (item.label.indexOf(query) > -1 || item.datasname.indexOf(query) > -1);
        }
      },
      transferRenderContentDatas (h, option) {
        return (
          <div>
            <span class="transfer_content_button" on-click={ event => this.transferShow(event, option) }><i class="fa fa-search" aria-hidden="true"></i></span>
            <span class="label show_label">{option.label}</span>
            <span class="label datasname">{option.datasname}</span>
          </div>
        );
      },

      async tableAuthSearchExpand (row, expanded) {
        if (expanded && !row.treeShow) {
          row.treeShow = true;
          let {func, datas} = await this.get('/userdataset/searchAPP/' + this.dialogAuthSearch.row.id + '/' + row.id);
          row.func = func;
          row.datas = datas;
        }
      },
      dialogAuthSearchInit () {
        this.dialogAuthSearch.row = {};
      },
      dialogAuthSearchOpen (row) {
        this.dialogAuthSearch.row = row;
        this.tableAuthSearch.url = '/userdataset/searchAPP/' + row.id;
        this.dialogAuthSearch.visible = true;
        this.tableWatch('tableAuthSearch');
      },
      dialogAuthSearchSave: async function () {
        this.dialogAuthSearchInit();
        this.dialogAuthSearch.visible = false;
      },
      windowOpen () {
        window.open('/safety/datas');
      },
    },
    watch: {
      'formDialog1.rentId': function () {
        this.remoteMethodOrgId();
        this.formDialog1.orgId = [];
      },
    },
    mounted: function () {
      this.tableWatch('table');
    },
  });
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="scss">
  .box-card {
    margin: 20px;
  }

  .createTimeSpan {
    display: block;
    margin-top: 34px;
  }

  @media screen and (max-width: 800px) {
    .createTimeSpan {
      margin-top: 0;
    }
    .box-card {
      margin: 0;
    }
  }

  .el-select {
    width: 100%;
  }
</style>

<style lang="scss">
  .form_item_user{
    margin-bottom: 0;
  }

  .user .el-switch__label {
    span {
      font-size: 12px;
    }
  }

  .user .portrait .cell{
    padding: 0 10px;
  }

  .user .__transfer .el-checkbox__label{
    .label{
      padding-right: 5px;
    }
    .name{

    }
    .show_appId{
      color: #0affce;
    }
    .show_rentId{
      color: #d35e56;
    }
  }
  ._refresh {
    &:hover {
      .refresh {
        animation: fa-spin 1.3s infinite linear;
      }
    }
  }

</style>
